package com.sdy.interceptor;

import java.util.Date;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.mysql.jdbc.StringUtils;
import com.sdy.model.Employer;
import com.sdy.util.AjaxDone;
import com.sdy.util.HttpUtil;

/*登陆拦截**/
public class LoginInterceptor implements Interceptor {
	private Employer dao = Employer.dao;
	public void intercept(ActionInvocation ai) {
		try {
			String actionKey = ai.getActionKey();
			if(!StringUtils.isNullOrEmpty(actionKey) && actionKey.startsWith("/admin")) {
				if(ai.getActionKey().equals("/admin/login") || ai.getActionKey().equals("/admin")) {
					ai.invoke();
				} else {
					String username = (String) ai.getController().getSession().getAttribute("username");
					if(StringUtils.isNullOrEmpty(username)) {
						ai.getController().redirect("/admin");
					} else {
						Employer emp = dao.getEmployerByIpAndUserId(username, HttpUtil.getIpAddr(ai.getController().getRequest()));
						if(emp != null) {
							System.out.println(System.currentTimeMillis());
							System.out.println(emp.getDate("lastLoginDate").getTime());
							if((System.currentTimeMillis() - emp.getDate("lastLoginDate").getTime())/(60 * 1000) <= 30) {
								//更新操作时间
								emp.set("lastLoginDate", new Date());
								emp.set("ip", HttpUtil.getIpAddr(ai.getController().getRequest()));
								emp.update();
								ai.invoke();
							} else {
								throw new RuntimeException("登陆超时，请重新登陆.");
							}
						} else {
							throw new RuntimeException("您的账号在别处登录，请重新登陆.");
						}
					}
				}
			} else {
				ai.invoke();
			}
		} catch (Exception e) {
			e.printStackTrace();
			ai.getController().redirect("/admin");
		}
	}
}
